/**
 * 
 */
package com.cipe.cmrs.controllers;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cipe.cmrs.model.Country;
import com.cipe.cmrs.model.Region;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.RegionService;
import com.cipe.cmrs.service.UserService;

/**
 * @author Incepio
 *
 */
@Controller
public class RegionController extends BaseController {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= -3823562098119817733L;
	@Autowired
	private RegionService		regionService;
	@Autowired
	private UserService					userService;
	@Autowired
	private CountryService  countryService;
	
	@RequestMapping("/secure/showAddRegion.do")
	public String showAddRegion(Model model) {
		model.addAttribute("region", new Region());
		model.addAttribute("regionaldirectors", userService.findAll());
		return "editRegion";
	}

	@RequestMapping("/secure/showEditRegion.do")
	public String showEditRegion(@RequestParam Integer id, Model model) {
		model.addAttribute("region", regionService.findById(id));
		model.addAttribute("regionaldirectors", userService.findAll());
		return "editRegion";
	}

	@RequestMapping("/secure/saveRegion.do")
	public String SaveRegion(@ModelAttribute("region") Region region, BindingResult result, Model model, HttpServletRequest request) {
		try {
			
			region = regionService.saveRegion(region, getUserId(request));
			saveMessage(request, getText("editRegion.message.success"));
			model.addAttribute("regionaldirectors", userService.findAll());
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		
		model.addAttribute("region", region);
		return "editRegion";
	}

	@RequestMapping("/secure/showRegionList.do")
	public String showRegionList(Model model) {
		model.addAttribute("regions", regionService.findAll());
		return "regionList";
	}
	
	@RequestMapping(value="/secure/loadCountries.do", method=RequestMethod.GET) 
	public @ResponseBody Map<String,String> loadCountriesViaAjax(@RequestParam Integer regionId, Model model) {
		Map<String, String> results = null;
		Region region = regionService.findById(regionId);
		
		if(region != null) { 
			
			List<Country> countries = countryService.getAllCountriesByRegion(regionId);
			//logger.debug
			 results = new LinkedHashMap<String, String>();
			/* Note: we could let Spring serialize the list of states automatically, but
			 	  usually this reports an error... for bidirectional mappings in the underyling entities.
			 */
			if(countries != null && !countries.isEmpty()) {
				for(Country country : countries) { 
					// TODO: this actually acts like a LIFO in the front end, try to sort them first... 
					results.put(country.getId().toString(), country.getDisplayName());
				}
			}

			results.put("director", (region.getRegionalDirector().getId() != null) ? 
					String.valueOf(region.getRegionalDirector().getId()) : "");
		}
		
		return results;
	}		
}
